package com.qujia.system.service.impl;

import com.qujia.common.annotation.DataScope;
import com.qujia.common.constant.UserConstants;
import com.qujia.common.core.domain.entity.SysDept;
import com.qujia.common.core.domain.entity.SysRole;
import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.common.utils.StringUtils;
import com.qujia.system.domain.SysPost;
import com.qujia.system.domain.SysUserPost;
import com.qujia.system.domain.SysUserRole;
import com.qujia.system.domain.XcxActualPaymentDto;
import com.qujia.system.mapper.*;
import com.qujia.system.service.ISysConfigService;
import com.qujia.system.service.ISysDeptService;
import com.qujia.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 用户 业务层处理
 *
 * @author qujia
 */
@Service
public class SysUserServiceImpl implements ISysUserService
{
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    public static final String DIC_TYPE_STAFF_SETTING = "staff_setting";
    public static final String DIC_LABEL_STAFF_ROLE_ID = "staff_role_id";


    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private SysDictDataMapper dictDataMapper;




    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user)
    {
        return userMapper.selectUserList(user);
    }
    /**
     * 根据条件分页查询角色为员工的用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectEmployeeList(SysUser user) {
        String roleId = dictDataMapper.selectDictValue(DIC_TYPE_STAFF_SETTING, DIC_LABEL_STAFF_ROLE_ID);
        user.setRoleIds(new Long[]{Long.valueOf(roleId)});
        return userMapper.selectRoleUserList(user);
    }

    @Override
    public List<SysUser> selectAllUserList() {
        return userMapper.selectAllUserList();
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName)
    {
        return userMapper.selectUserByUserName(userName);
    }


    /**
     * 根据用户ids获取用户名字的字符串你和
     *
     * @param ids 用户信息
     * @return 用户信息集合信息
     */
    public String selectUserName(String ids){
        String [] id=ids.split(",");
        String names="";
        if(id==null){
            return "暂无加油员";
        }else if(id.length>1) {
            for (String m : id) {
                SysUser sysUser = userMapper.selectUserById(Long.parseLong(m.trim()));
                names = names + sysUser.getNickName() + ",";
            }
        }else  if(id.length==1){
            SysUser sysUser = userMapper.selectUserById(Long.parseLong(id[0].trim()));
            names = names + sysUser.getNickName() ;
        }
        return  names;
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId)
    {
        return userMapper.selectUserById(userId);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName)
    {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        StringBuffer idsStr = new StringBuffer();
        for (SysRole role : list)
        {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName)
    {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        StringBuffer idsStr = new StringBuffer();
        for (SysPost post : list)
        {
            idsStr.append(post.getPostName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param userName 用户名称
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(String userName)
    {
        int count = userMapper.checkUserNameUnique(userName);
        if (count > 0)
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(SysUser user)
    {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user)
    {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin())
        {
            throw new CustomException("不允许操作超级管理员用户");
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user)
    {
        // 新增用户信息
        if(user.getSupremeLevelName()!=null){
            SysUser aUser =   userMapper.getByUserName(user.getSupremeLevelName());
            user.setSupremeLevelId(aUser.getUserId());
        }
        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user)
    {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user)
    {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user)
    {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar 头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar)
    {
        return userMapper.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user)
    {
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password)
    {
        return userMapper.resetUserPwd(userName, password);
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user)
    {
        Long[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roles)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0)
            {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user)
    {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotNull(posts))
        {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Long postId : posts)
            {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            if (list.size() > 0)
            {
                userPostMapper.batchUserPost(list);
            }
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public int deleteUserById(Long userId)
    {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    public int deleteUserByIds(Long[] userIds)
    {
        for (Long userId : userIds)
        {
            checkUserAllowed(new SysUser(userId));
        }
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     *
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new CustomException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList)
        {
            try
            {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u))
                {
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    this.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    user.setUpdateBy(operName);
                    this.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public boolean getUserRole(LoginUser currentUser) {
        List<SysRole> roleList = currentUser.getUser().getRoles();
        boolean flag=false;
        for(SysRole role : roleList){
            if(role.getRoleId()==1){
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 根据角色判断用户对应的油站id
     * @param currentUser
     * @return
     */
    @Override
    public String getUserRoleDeptId(LoginUser currentUser) {
        //根据当前用户的detpid ，查看dept是组织机构中的哪个站。 jibie 0平台。1为集团， 2为油站
        SysDept sysDept = sysDeptService.selectDeptById(currentUser.getUser().getDeptId());
        String deptid="";
        if(sysDept!=null){
            if(sysDept.getJiBie()==2){
                deptid =sysDept.getDeptId().toString();
            }else if(sysDept.getJiBie()==1){
                SysDept dept = new SysDept();
                dept.setParentId(sysDept.getDeptId());
               List<SysDept> list= sysDeptService.selectDeptList(dept);
               if(list!=null&& list.size()>0){
                   for(SysDept sd:list){
                       if(deptid==""){
                           deptid = sd.getDeptId().toString();
                       }else{
                           deptid =deptid+","+ sd.getDeptId().toString();
                       }
                   }
               }
            }
        }
        return deptid;
    }

    /**
     * 修改用户是否是代理
     * @param user
     * @return
     */
    @Override
    public int updateUserAgentFlag(SysUser user) {
        return userMapper.updateUserAgentFlag(user);
    }

    /**
     * 根据电话号码查询用户名(手机号登陆用)
     * @param phoneNumber
     * @return
     */
    public List<String> selectUsernameByPhoneNumber(String phoneNumber){
        return userMapper.selectUsernameByPhoneNumber(phoneNumber);
    }

    /**
     * 获取等级为五或六的用户
     * @return
     */
    @Override
    public List<SysUser> getUserLevel(Integer level) {

        if (level == null){
           return userMapper.selecUserLevel(null);
        }
        if (level == 1){
          return   userMapper.selecUserLevel("5");
        }

       return userMapper.selecUserLevelIsSix("6");

    }

    @Override
    public List<SysUser> getLevelUserSix() {
        return userMapper.getLevelUserSix();
    }

    @Override
    public String getEmployeeSign(Long userId) {
        return userMapper.getUserByUserId(userId);
    }

    @Override
    public SysUser selectUserByPhoneNumber(String phoneNumber, Long enterpriseId) {
        if(StringUtils.isNotEmpty(phoneNumber) && Objects.nonNull(enterpriseId)){
            return userMapper.selectUserByPhoneNumber(phoneNumber,enterpriseId);
        }
        return null;
    }

    @Override
    public SysUser getById(Long userId){
        return userMapper.getById(userId);
    }

    @Override
    public List<String> selectByEmployee(List<Long> stationIdList) {
        return userMapper.selectByEmployee(stationIdList);
    }

    @Override
    public XcxActualPaymentDto xcxActualPaymentDetail( XcxActualPaymentDto xcxActualPayment) {
        return userMapper.xcxActualPaymentDetail(xcxActualPayment);
    }

    @Override
    public int xcxActualPayment( XcxActualPaymentDto xcxActualPayment) {
        return userMapper.xcxActualPayment(xcxActualPayment);
    }

    @Override
    public int updateEmployeeShow(List<Long> stationIdList, String employeeShow) {
        return userMapper.updateEmployeeShow(stationIdList,employeeShow);
    }

    @Override
    public List<String> getLevelList() {
        return userMapper.getLevelList();
    }



}
